const { modelName } = require("../models/studentModel");
const mongoose = require('mongoose');
const jwt = require('jsonwebtoken');

async function register(req, res) {
    let attr = await mongoose.model(modelName).find({ phone: req.body.phone });
    if (attr.length == 0) {
        //学生注册
        if (req.body.phone.length == 11) {
            await mongoose.model(modelName).create(req.body);
            res.send({
                message: '注册成功',
                code: 1
            });
        } else {
            res.send({
                message: '注册失败',
                code: -1
            });
        }
    } else {
        res.send({
            message: "账号已存在,注册失败",
            code: 0
        });
    }
}

//学生登录
async function login(req, res) {
    //查找用户
    let result = await mongoose.model(modelName).find({ phone: req.body.phone, password: req.body.password });
    if (result.length > 0) {
        //生成token并返回到前端
        const token = jwt.sign(
            { user: result[0] }, //  用户信息
            'user',  // 密钥，任意字符串
            { expiresIn: 10000 }  //设置有效期,纯数字以秒为单位， 支持字符串 "10 days"  "8h" 
        );

        res.send({
            message: '登录成功',
            code: 200,
            token: "Bearer " + token,
            data: result[0]
        });
    } else {
        //登录失败
        res.send({
            message: '登录失败，用户不存在或输入错误',
            code: -1,
        });
    }
}
//修改学生
async function changeStudent(req, res) {
    const result = await mongoose.model("studentModel").updateOne({ phone: `${req.body.phone}` }, { avatar: `${req.body.avatar}`, name: `${req.body.name}`, gender: `${req.body.gender}` });
    res.send({
        message: '修改成功',
        code: 10,
        data: result
    });
}
//获取当前登录用户信息
async function getUserInfo(req, res) {
    let info = req.body.token;
    let token = info.split(' ')[1];
    const user = jwt.verify(token, 'user');
    let result = await mongoose.model(modelName).find({ phone: user.user.phone });
    res.send(...result);
}
//获取当前登录用户信息
async function getstudents(req, res) {
    let result = await mongoose.model(modelName).find();
    res.send(result);
}
module.exports = {
    register,
    login,
    changeStudent,
    getUserInfo,
    getstudents
};